<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>peerB</title>
</head>
<body>
<video id="remoteVideo" autoplay="autoplay" controls></video>

</body>
<script type="text/javascript">
	let peerConnB, wsKey, isPlaying

	let tempTimer = setInterval(() => {
		console.log()
		if(remoteVideo.currentTime > 0){
			clearInterval(tempTimer)
			isPlaying = true
		}
	}, 1000)

	var ws = new WebSocket('ws://172.16.200.188:3030');

	ws.onopen = function(evt) {
		console.log('Connection open ...');
		ws.send(JSON.stringify({type: 'watcher'}))
	};

	ws.onmessage = function(evt) {
		let tempData = JSON.parse(evt.data)
		console.log(tempData)
		if(isPlaying) return
		switch (tempData.type){
			case 'createAnswer':
				peerBCreateAnswer(tempData.data)
				break
			case 'candidateToB':
				candidateToB(tempData.data)
				break
			case "backKey":
				wsKey = tempData.data
				break
		}
	};

	ws.onclose = function(evt) {
		console.log('Connection closed.');
	};

	function createPeerB(){
		let configuration = {"iceServer": [{"url": "stun: stun.l.google.com:19302"}]}

		peerConnB = new RTCPeerConnection(configuration)
		peerConnB.addEventListener('icecandidate', onIceCandidDateB)
		peerConnB.addEventListener('iceconnectionstatechange', onIceStateChangeB)
		// 获取到远端流
		peerConnB.addEventListener('track', gotRemoteStream)
	}
	createPeerB()

	async function peerBCreateAnswer(desc){
		// 设置远程描述
		try{
			await peerConnB.setRemoteDescription(desc)
			onSetRemoteSuccess(peerConnB)
		}catch (e) {
			console.log(e)
		}

		// 创建answer
		try{
			const answer = await peerConnB.createAnswer( )
			onCreateAnswerSuccess(answer)
		}catch (e) {
			console.log(e)
		}

	}

	async function onCreateAnswerSuccess(desc){
		console.log(desc,'===desc===desc===desc====desc===desc====')
		try{
			await peerConnB.setLocalDescription(desc)

			let obj = JSON.stringify({
				type: 'createAnswer',
				data: desc,
				key: wsKey
			})
			ws.send(obj)

			onSetLocalSuccess(peerConnB)
		}catch (e) {
			console.log(e)
		}

	}

	function onSetLocalSuccess(pc){

	}
	function onSetRemoteSuccess(pc){

	}

	function onIceStateChangeB(evt){

	}

	async function onIceCandidDateB(evt){
		try{
			if(evt.candidate){
				let candObj = JSON.stringify({
					type: 'candidateToA',
					data: evt.candidate,
					key: wsKey
				})
				ws.send(candObj)
			}
		}catch (e){console.log(e)}
	}

	async function candidateToB(data){
		try{
			await peerConnB.addIceCandidate(data)
			onAddIceCandidateSuccess(peerConnB)
		}catch (e){}
	}

	function gotRemoteStream(e){
		console.log('设置远端流：')
		console.log(e)
		if(remoteVideo.srcObject != e.streams[0]){
			remoteVideo.srcObject = e.streams[0]
		}
	}

</script>
</html>
